package com.jwyming.secKilling;

import org.apache.log4j.Logger;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * Created by user on 2017/4/4.
 */
public class JobExecutor {
    static Logger logger = Logger.getLogger(JobExecutor.class.getName());

    public static void main(String[] args) throws Exception {

        ConfigInfo configInfo = new ConfigInfo();
        List<ConfigItem> configItems = configInfo.getConfigItems();

        int threads = configItems.size() > 5 ? 5 : configItems.size();

        ScheduledExecutorService ex = new ScheduledThreadPoolExecutor(threads);

        for(int i = 0; i < configItems.size(); i++) {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date startDate = sdf.parse(configItems.get(i).getProperty("startTime"));
            long delay = startDate.getTime() - System.currentTimeMillis();
//        logger.info("delay=" + delay);
            ScheduledFuture<String> result = null;
            int executeTimes = 0;
            int maxRetryTimes = Integer.parseInt(configItems.get(i).getProperty("maxRetryTimes"));

            logger.info("开始执行第" + (executeTimes + 1) + "次。。。");
            result = ex.schedule(new SecKillingTask(executeTimes++, configItems.get(i)),
                    delay, TimeUnit.MILLISECONDS);
            while (executeTimes < maxRetryTimes) {
                if (!result.get().equalsIgnoreCase("Success")) {
//                Thread.sleep(1000);
                    logger.info("============================================");
                    logger.info("开始执行第" + (executeTimes + 1) + "次。。。");
//                result = ex.schedule(new SecKillingTask(executeTimes++, configItem),
//                        startDate.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
                    result = ex.schedule(new SecKillingTask(executeTimes++, configItems.get(i)),
                            1, TimeUnit.SECONDS);
                } else {
                    logger.info("执行" + executeTimes + "次后成功");
                    break;
                }

            }
            if (executeTimes >= maxRetryTimes) {
                logger.error("重试" + executeTimes + "次后仍然失败！！！");
            }
        }






//        ex.shutdown();

    }
}
